//
//  JPVideoVC.m
//  Jpod
//
//  Created by zenox on 2022/4/5.
//

#import "JPVideoVC.h"
#import <AVFoundation/AVFoundation.h>


@interface JPVideoVC ()<AVAssetResourceLoaderDelegate>
// 播放器的Layer
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
/* 播放器 */
@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) UIButton *playButton;

@property (nonatomic, strong) AVPlayerItem *currentItem;

@end

@implementation JPVideoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self video];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.player play];
}
- (AVPlayer *)player
{
    if (!_player) {
        // 初始化Player和Layer
        _player = [[AVPlayer alloc] init];
    }
    return _player;
}

- (void)video{
    
    /**
        videoGravity //视频播放时的拉伸方式
        param:
            AVLayerVideoGravityResizeAspect //等比例填充，直到一个维度到达区域边界。部分机型有黑边
            AVLayerVideoGravityResizeAspectFill //等比例填充，直到填充满整个视图区域，其中一个维度的部分区域会被裁剪
            AVLayerVideoGravityResize //非均匀模式。两个维度完全填充至整个视图区域。会变形
    */
    
    //创建AVPlayerLayer
    self.playerLayer = [[AVPlayerLayer alloc] init];
    //frame
    self.playerLayer.frame = self.view.bounds;
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;

    //去除黑边
    //使playerLayer光栅化(即位图化)，关闭了图层的blending(混合)。
    self.playerLayer.shouldRasterize = YES;
    //显式指定光栅化的范围，这样能保证视频的显示质量，不然容易出现视频质量显示不佳。
    self.playerLayer.rasterizationScale = [UIScreen mainScreen].scale;

    //在view的layer上添加layer
    [self.view.layer addSublayer:self.playerLayer];
    
    //方式二
    //类方法通过URl地址创建要播放的对象 可以是本地内容也可以是在线内容
//    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.url]];

    //切换视频资源
//    [self.player replaceCurrentItemWithPlayerItem:item];

    [self.playerLayer setPlayer:self.player];
    //方式一
    //通过设备相册里面的内容 创建一个要播放的对象
//    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL: [NSURL URLWithString:@"file:///var/mobile/Containers/Data/Application/844D2D16-AEAB-4646-B12E-157A10B041B9/Documents/output-2022-04-06-21:12:23.mp4"] options: nil];
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL: [NSURL URLWithString:@"file:///var/mobile/Media/DCIM/100APPLE/IMG_0023.MOV"] options: nil];

    [[urlAsset resourceLoader] setDelegate: self queue: dispatch_get_main_queue()];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:urlAsset];
    self.currentItem = item;
    
    [self.player replaceCurrentItemWithPlayerItem:self.currentItem];
    
    [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
   
    [self.view addSubview:self.playButton];


    //通过KVO来观察status属性的变化，来获得播放之前的错误信息
    [_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
                     
    self.player.automaticallyWaitsToMinimizeStalling = NO;
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [change[NSKeyValueChangeNewKey] intValue];
        switch (status) {
            case AVPlayerStatusFailed:
            {
                NSLog(@"url有误");
            }
                break;
            case AVPlayerStatusReadyToPlay:
            {
                NSLog(@"准备好播放了");
            
            }
                break;
            case AVPlayerStatusUnknown:
            {
                NSLog(@"视频资源出现未知错误");
            }
                break;
            default:
                break;
        }
    }
}

- (UIButton *)playButton{
    if (_playButton == nil) {
        self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.playButton.frame = CGRectMake(0, 0, 50, 50);
        self.playButton.center = self.view.center;
//                self.playButton.backgroundColor = [UIColor redColor];
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
//        [self.playButton se]
        [self.playButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _playButton;
}

- (void)btnClick:(id)sender{
    
    [self.player play];
}

#pragma mark - 设置播放的视频
- (void)setUrlString:(NSString *)urlString
{
    return;
    _urlString = urlString;
   
    NSURL *url = [NSURL URLWithString:urlString];
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
    self.currentItem = item;
    
    [self.player replaceCurrentItemWithPlayerItem:self.currentItem];
    
    [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_currentItem];
    
}
- (void)moviePlayDidEnd:(NSNotification *)notification {
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
//        [weakSelf.progressSlider setValue:0.0 animated:YES];
//        weakSelf.playOrPauseBtn.selected = NO;
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //模态消失
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"UIImagePickerControllerMediaType"]] isEqualToString:@"public.image"]) {//图片
        UIImage *image;
        if (picker.allowsEditing)
        {
            image = [info objectForKey:UIImagePickerControllerEditedImage];
            
        }else
        {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        //    NSString *aPath = [NSString stringWithFormat:@"%@/Documents/%@.jpg",NSHomeDirectory(),@"test"];//生成路径
        NSData *imgData = UIImageJPEGRepresentation(image, 0.1);// 压缩图片 参数0-1 1最大 0无限接近 最小15k左右
        //    [imgData writeToFile:aPath atomically:YES];
        
    }else if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"UIImagePickerControllerMediaType"]] isEqualToString:@"public.movie"]){//视频
        
        
        NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
        NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
        NSURL *newVideoUrl ; //一般.mp4
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
        [picker dismissViewControllerAnimated:YES completion:nil];
        [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
    
    }
}

//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getFileSize:(NSString *)path
{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}

//此方法可以获取视频文件的时长。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}

- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                               outputURL:(NSURL*)outputURL
                         completeHandler:(void (^)(AVAssetExportSession*))handler
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    //  NSLog(resultPath);
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
                 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
                 
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                 
                 [self alertUploadVideo:outputURL];
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
         
     }];
}


-(void)alertUploadVideo:(NSURL*)URL{
    CGFloat size = [self getFileSize:[URL path]];
    NSString *message;
    NSString *sizeString;
    CGFloat sizemb= size/1024;
    if(size<=1024){
        sizeString = [NSString stringWithFormat:@"%.2fKB",size];
    }else{
        sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
    }
    
    if(sizemb<2){
        [self uploadVideo:URL];
    }
    else if(sizemb<=5){
        message = [NSString stringWithFormat:@"视频%@，大于2MB会有点慢，确定上传吗？", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                  message: message
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间（沙盒）
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self uploadVideo:URL];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }/*else if(sizemb>5){
        message = [NSString stringWithFormat:@"视频%@，超过5MB，不能上传，抱歉。", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                  message: message
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    */
    
}

-(void)uploadVideo:(NSURL*)URL{
    
    
    NSData *data = [NSData dataWithContentsOfURL:URL];
    
//    [Manage requestToUploadAttachmentsDataWith:^(NSDictionary *base) {
//        if ([base[@"errno"] intValue] == 200) {
//            [SVProgressHUD showInfoWithStatus:[base objectForKey:@"err"]];
//        }else{
//            [SVProgressHUD showInfoWithStatus:[base objectForKey:@"err"]];
//        }
//    } taskId:self.taskId fileImg:nil URL:URL enclosureType:self.taskId fileVideo:data];
}
@end
